import { Alert } from 'react-native'
import Config from 'react-native-config'
import { dataType } from '@pier88health/p8h-common'
import umeng from './UmengAnalytics'
import ANALYTICS_EVENT_ENUM from './ANALYTICS_EVENT_ENUM'

const envType = Config.ENV_TYPE
type ANALYTICS_EVENT_KEY = keyof typeof ANALYTICS_EVENT

export const ANALYTICS_EVENT = ANALYTICS_EVENT_ENUM

type EventObjProps = {
  [key: string]: string | number
}

export default {
  initUM: () => {
    umeng.init?.()
  },
  profileSignInWithPUID: (userName: string) => {
    umeng.profileSignInWithPUID(userName)
  },
  onPageStart: (page?: string) => {
    console.log('---------onPageStart', page)
    if (!page) return
    umeng.onPageStart(page)
  },
  onPageEnd: (page?: string) => {
    console.log('---------onPageEnd', page)
    if (!page) return
    umeng.onPageEnd(page)
  },
  onWrapperAttrDurations: (eventId: string, value: string, startTime: number) => {
    const eventObj = ANALYTICS_EVENT[eventId as ANALYTICS_EVENT_KEY]
    const { eventLabel, eventParameter } = eventObj
    if (envType !== 'production' && (!eventId || !eventLabel || !eventParameter || !value)) {
      Alert.alert(
        'Event required parameter is not specified',
        `${eventId} - ${eventLabel} - ${eventParameter} - ${value}`,
      )
      return
    }
    const millsSeconds = new Date().getTime() - startTime
    umeng.onEventWithMapAndDurations(eventId, { [eventParameter]: value, durations: millsSeconds }, millsSeconds)
  },
  onEventLabel: (eventId: string) => {
    console.log('eventId', eventId)
    if (!eventId) {
      return
    }
    const eventObj = ANALYTICS_EVENT[eventId as ANALYTICS_EVENT_KEY]
    const { eventLabel } = eventObj
    if (envType !== 'production' && (!eventId || !eventLabel)) {
      Alert.alert(
        'Event required parameter is not specified',
        `${eventId} - ${eventLabel}`,
      )
      return
    }
    umeng.onEventWithLabel(eventId, eventLabel)
  },
  onEvent: (eventId: string, info?: EventObjProps) => {
    const isError = typeof info !== 'undefined' && (dataType.isNull(info) || !dataType.isObject(info))
    if (envType !== 'production' && isError) {
      Alert.alert(
        'Event required parameter is not specified',
        `${eventId}`,
      )
      return
    }
    const firstKey = info && Object.keys(info)[0]
    if (envType !== 'production' && (!eventId || (firstKey && typeof info[firstKey] === 'undefined'))) {
      Alert.alert(
        'Event required parameter is not specified',
        `${eventId} - ${firstKey} - ${JSON.stringify(info)}`,
      )
      return
    }
    umeng.onEventWithMap?.(eventId, info || {})
  },
  profileSignOff: () => umeng.profileSignOff(),
}
